# coding=utf-8
'''
main function：主要实现把iOS 项目中的翻译字符串写入到excel中
'''
#################
#

import xlwt  # 写excel文件
import os
import shutil
import datetime
import sys

reload(sys)
sys.setdefaultencoding('utf8')


def languageString(inputKey,lines):
    stringValue = ''
    for line in lines:
        if '=' in line:
            key = line.split('=')[0].strip()
            if inputKey == key:
                stringValue = line.split('=')[1].strip()
                break
    return stringValue

def getFiles(path, suffix):
    return [os.path.join(root, file) for root, dirs, files in os.walk(path) for file in files if file.endswith(suffix)]

def getStringFilesPath():
    paths = getFiles("/Users/alic/Work/HomeMate/HMWorkSpace/HomeMate2_Trunk/HomeMate/Resources/Strings",'Localizable.strings')
    # print os.path.dirname(path)
    # print os.path.basename(path)

    data = []
    for path in paths[:]:
        languageName = os.path.splitext(os.path.dirname(path).split('/')[-1])[0]
        if languageName == 'zh-Hans': #简体中文
            data.insert(0,path)
            paths.remove(path)
        elif languageName == 'en': #英文
            data.append(path)
            paths.remove(path)
        elif languageName == 'Base':
            paths.remove(path)
        elif languageName == 'zh-Hant-TW':
            data.append(path)
            paths.remove(path)

    data.extend(paths)
    return data

def languageName(path):
    return os.path.splitext(os.path.dirname(path).split('/')[-1])[0]


def stringToExcel(excelName):

    # 新建一个excel文件
    file = xlwt.Workbook(encoding='utf-8', style_compression=0)
    # 新建一个sheet
    sheet = file.add_sheet('data')

    # 翻译文件路径
    filePaths = getStringFilesPath()

    # 第一行，第一列 固定值 Key
    row = 0
    sheet.write(row, 0, 'Key')

    # 第一行，第二列开始 语言名称
    for i,path in enumerate (filePaths):
        # 根据路径获取语言名称
        sheet.write(row, i+1, languageName(path))

    row = row + 1 # 换行

    # 数组中第一个元素是中文翻译文件的路径
    zh_filePath = filePaths[0]
    filePaths.remove(zh_filePath)

    blankDict = {}
    fileLines = []
    for path in filePaths:

        fileHandle = open(path, 'r')
        lines = fileHandle.readlines()

        name = languageName(path)
        blankDict[name] = []
        fileLines.append((name,lines))


    # 中文文件作为基础文件，其他文件参照中文文件来的顺序俩写入对应的翻译内容
    with open(zh_filePath, 'r') as f:
        for line in f.readlines():
            if ('=' in line):
                key = line.split('=')[0].strip()
                value = line.split('=')[1].strip()

                sheet.write(row, 0, key)    # 第row行第一列
                sheet.write(row, 1, value)  # 第row行第二列

                # 第row行第三列开始是中文之外的其他语言
                for i, (name,lines) in enumerate(fileLines):
                    lanValue = languageString(key,lines)
                    if len(lanValue) > 1:
                        sheet.write(row, i+2, lanValue)
                    else:
                        blankDict[name].append(key)
                row = row + 1 # 换行

    file.save(excelName)

    for key in blankDict:
        print key
        for values in blankDict[key]:
            print values
        print '\n\n'


def mkdir(path):
    # 去除首位空格
    path = path.strip()
    # 去除尾部 \ 符号
    path = path.rstrip("\\")

    # 删除旧目录
    if os.path.exists(path):
        # os.removedirs(path) # 不能删除非空文件目录
        shutil.rmtree(path)  # 递归删除文件夹 可以删除非空文件夹

    # 创建新目录
    os.makedirs(path)
    return path

def exportAllStrings():

    # 创建翻译存储目录
    dir = mkdir("txt翻译")

    # 翻译文件路径
    filePaths = getStringFilesPath()

    for strPath in filePaths:
        with open(strPath,'r') as f:
            name = languageName(strPath)
            path = dir + "/" + name + '.txt'
            with open(path, 'wb') as f2:
                row = 0
                for line in f.readlines():
                    if ('=' in line):
                        if name == 'zh-Hans':
                            print str(row)
                        f2.write(line.encode("utf-8"))
                        row = row + 1

                if name == 'zh-Hans':
                    print "\n"
                    print '----------------------------------------------------------------------------------------------'
                    print '--------------------------------------  ' + name +'  ---------------------------------------------'
                    print '----------------------------------------------------------------------------------------------'

def exportSpecificString(inpuKey):

    # 创建翻译存储目录
    # dir = mkdir("指定翻译")
    # path = dir + "/" + '翻译' + '.txt'

    # 翻译文件路径
    filePaths = getStringFilesPath()

    # with open(path, 'wb') as f2:
    # f2.write(name.encode("utf-8"))
    # f2.write('\n'.encode("utf-8"))
    # f2.write(line.encode("utf-8"))

    # 在key字符串两边添加双引号
    inpuKey = '\"' + inpuKey + '\"'
    for strPath in filePaths:
        with open(strPath, 'r') as f:
            for line in f.readlines():
                if ('=' in line):
                    key = line.split('=')[0].strip()
                    if key == inpuKey:
                        print languageName(strPath)
                        print line
                        break








if __name__ == "__main__":

    print(datetime.datetime.now())
    print '\n'

    # stringToExcel('v4.4翻译.xls')
    # exportAllStrings()
    exportSpecificString("Localizable_MixPad_NoDevice_Tip")

    print '\n'
    print(datetime.datetime.now())